import { EventDispatcher } from '../core/EventDispatcher';
import UIMgr from './UIMgr';
import { NetEvent } from '../core/NetEvent';
import { C2SCommond, S2CCommond, ServerRes } from '../define/CSCommand';
import ViewMgr from './ViewMgr';

export default class ServerMgr extends EventDispatcher {
  public static _viewManager: ServerMgr;
  //获取单例对象
  public static get ins(): ServerMgr {
    if (ServerMgr._viewManager == null) {
      ServerMgr._viewManager = new ServerMgr();
      ServerMgr._viewManager.eventInit();
    }
    return ServerMgr._viewManager;
  }

  public eventInit(): void {
    //初始化一些事件
  }

  /**
   * 发送事件  当作逻辑处理器吧
   */
  public send2S(EventType: string, data?: any, bubbles?: boolean, cancelable?: boolean): void {
    let event: any = NetEvent.createrEvent(EventType, bubbles, cancelable, data);

    //不同分发了 这个伪造个处理的
    //this.dispatchEvent(event);

    this.dealC2SCommond(EventType, data);
  }

  /**
   *
   *模拟请求下发
   */
  public s2cArr: ServerRes[] = [];
  public send2C(ComKey: S2CCommond, data: any = null): void {
    this.s2cArr.push({ key: <string>ComKey, data: data });
  }
  public aiSend: boolean = false;
  public doSend2C(): void {
    let cmds: ServerRes[] = this.s2cArr;
    this.s2cArr = [];
    if (this.aiSend) {
      this.filterAiCmds(cmds);
    }
    if (cmds.length > 0) ViewMgr.ins.emit(S2CCommond.S2C_BASE_COMMAND, { command: cmds });
  }

  private filterAiCmds(cmds: ServerRes[]): void {
    //不要表现的命令
    let noNeedShowKey: S2CCommond[] = [
      S2CCommond.S2C_Deal_Cards_From_Getheap,
      S2CCommond.S2C_DisHeap_To_Getheap,
      S2CCommond.S2C_DisAllCard,
      S2CCommond.S2C_Spend_Hero_Power,
      S2CCommond.S2C_Use_Single_Card,
      S2CCommond.S2C_Burn_Single_Card,
      S2CCommond.S2C_Hero_Resume_Power,
      S2CCommond.S2C_Add_Power,
      S2CCommond.S2C_Cards_Update,
      S2CCommond.S2C_Add_To_Hand,
    ];
    let noNeed: ServerRes[] = [];
    //ai发送的话有几个 不需要表现
    for (let i: number = 0; i < cmds.length; i++) {
      if (noNeedShowKey.indexOf(cmds[i].key) >= 0) {
        noNeed.push(cmds[i]);
      }
    }
    while (noNeed.length > 0) {
      let sermsg: ServerRes = noNeed.splice(0, 1)[0];
      if (sermsg) {
        let index: number = cmds.indexOf(sermsg);
        if (index >= 0) {
          cmds.splice(index, 1);
        }
      }
    }
  }

  //缓存下发请求
  private s2cArr_temp: ServerRes[] = [];
  public send2C_temp(ComKey: S2CCommond, data: any = null): void {
    this.s2cArr_temp.push({ key: <string>ComKey, data: data });
  }
  public send2C_freshTemp(): void {
    for (let i: number = 0; i < this.s2cArr_temp.length; i++) {
      this.s2cArr.push(this.s2cArr_temp[i]);
    }
    this.s2cArr_temp = [];
  }

  private dealC2SCommond(event: C2SCommond, paras: any): void {
    //这个地方开始伪造
    switch (event) {
      case C2SCommond.C2S_Enter_Battle:
        break;
    }
  }
}
